/* $Id: solaris.c,v 1.1 2005/06/20 16:34:28 jfb Exp $ */
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Network interface layering code
 *
 * The functions in here gather information on the network interfaces
 * available on the running system, and store the information in a list of
 * system-independent structures.  The code in this file is getting somewhat
 * hairy due to all the tricks we have to do to gather information, since
 * there are about a million different ways to get to it, but none is really
 * portable.
 *
 * Before making any modifications in here, make sure to test on all supported
 * platforms to avoid breaking functionality.
 */

#include <sys/param.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/socket.h>

#include <net/if.h>

#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/if_media.h>

#include <ifaddrs.h>

#elif defined(__linux__)
#include <net/if_arp.h>
#endif

#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>


#include "if.h"
#include "dlink.h"
#include "pforge.h"

#define PFIF_NBIF_INIT  24
#define PFIF_NBIF_INCR  10



extern struct pf_netif_ops pf_loop_ops;
extern struct pf_netif_ops pf_ether_ops;


static PF_NETIF* pf_netif_fromifreq    (int, struct ifreq *);

static PF_NETIF* pf_netif_alloc      (void);
static void      pf_netif_free       (PF_NETIF *);
static int       pf_netif_probe_bsd  (void);
static int       pf_netif_xlateflags (int);


static const struct pf_netif_type {
	char   ift_desc[32];
	struct pf_netif_ops *ift_opv;
} pf_netif_types[] = {
	{ "",                     NULL },
	{ "other",                NULL },
	{ "X25 to IMP",           NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Ethernet",             &pf_ether_ops },
	{ "",                     NULL },
	{ "Token Bus",            NULL },
	{ "Token Ring",           NULL },
	{ "",                     NULL },	/* 10 */
	{ "StarLAN",              NULL },
	{ "Proteon 10Mb ring",    NULL },
	{ "Proteon 80Mb ring",    NULL },
	{ "Hyperchannel",         NULL },
	{ "FDDI",                 NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Basic ISDN",           NULL },	/* 20 */
	{ "Primary ISDN",         NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Loopback",             &pf_loop_ops },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 30 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "RS-232",               NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "ATM",                  NULL },
	{ "",                     NULL },
	{ "SONET",                NULL },
	{ "",                     NULL },	/* 40 */
	{ "",                     NULL },
	{ "Localtalk",            NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Modem",                NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 50 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 60 */
	{ "",                     NULL },
	{ "Fast Ethernet",        NULL },
	{ "ISDN",                 NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 70 */
	{ "IEEE 802.11",          NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 80 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 90 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Myrinet",              NULL },
	{ "",                     NULL },	/* 100 */
};

#define NB_IFTYPES   (sizeof(pf_netif_types)/sizeof(struct pf_netif_type))


/* flag translation table */
static const int pf_netif_fltab[32] = {
	PFIF_FL_UP,
	PFIF_FL_BCAST,
	0,
	PFIF_FL_LOOPBACK,
	PFIF_FL_PTP,
	0,
	0,
	0,
	PFIF_FL_PROMISC,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
};


/* global interface table */
static PF_NETIF        *pf_netif_tab[PFIF_MAXIF];
static pthread_mutex_t  pf_netif_mtx = PTHREAD_MUTEX_INITIALIZER;


/*
 * pf_netif_init()
 *
 */
int
pf_netif_init(void)
{
	int ret;
	PF_NETIF *ifp;

	ret = pthread_mutex_init(&pf_netif_mtx, NULL);
	if (ret != 0) {
		return (-1);
	}

	return (0);
}


/*
 * pf_netif_cleanup()
 *
 */
void
pf_netif_cleanup(void)
{
	int i;

	for (i = 0; i < PFIF_MAXIF; i++) {
		if (pf_netif_tab[i] == NULL)
			continue;

		pf_netif_free(pf_netif_tab[i]);
		pf_netif_tab[i] = NULL;
	}

	(void)pthread_mutex_destroy(&pf_netif_mtx);
	pf_netif_mtx = PTHREAD_MUTEX_INITIALIZER;
}

/*
 * pf_netif_probe()
 *
 * Probe the system through the appropriate interface to rebuild the library's
 * view of the system's available interfaces.
 * Returns the number of interfaces found on success, or -1 on failure.
 */
int
pf_netif_probe(void)
{
	int nbif, sfd, ifblen, pifblen;
	size_t len;
	caddr_t ifptr;
	struct ifconf ifc;
	PF_NETIF *nif;
	struct ifreq *ifr;

#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
	return pf_netif_probe_bsd();
#endif

	sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sfd < 0) {
		return (-1);
	}

	/*
	 * Try ioctl's until we get all interfaces.
	 * on Solaris, a SIOCGIFCONF ioctl will return EINVAL if the buffer
	 * of the ifconf structure is not large enough, while BSD systems
	 * will fill it with as much info as it can before it's full.
	 *
	 * On Linux, SIOCGIFCONF only returns the list of interfaces which have
	 * an IP address set.  This is somewhat annoying, as the only other way
	 * I have found to gather the information is through the /proc
	 * filesystem.
	 *
	 * In any cases, we start with a really big buffer to avoid some obscure
	 * problems.
	 */
	pifblen = 0;
	ifblen = 8192;
	for (;;) {
		ifc.ifc_buf = malloc(ifblen);
		if (ifc.ifc_buf == NULL) {
			return (-1);
		}

		ifc.ifc_len = ifblen;
		if (ioctl(sfd, SIOCGIFCONF, &ifc) < 0) {
			free(ifc.ifc_buf);
			return (-1);
		}
		if (ifc.ifc_len <= ifblen)
			break;
		free(ifc.ifc_buf);
		ifblen *= 2;
	}

	nbif = 0;
	for (ifptr = ifc.ifc_buf; ifptr < ifc.ifc_buf + ifc.ifc_len;) {
		ifr = (struct ifreq *)ifptr;
		printf("loading `%s' (%d)\n", ifr->ifr_name,
		    ifr->ifr_addr.sa_family);

		len = sizeof(struct ifreq);
		ifptr += len;

		nif = pf_netif_fromifreq(sfd, ifr);

		if (pf_netif_add(nif, nif->if_index) < 0) {
			return (-1);
		}
		nbif++;
	}

	free(ifc.ifc_buf);
	(void)close(sfd);

	return (nbif);
}

/*
 * pf_netif_create()
 *
 * Create a new network interface of type <type> and with name <name>.
 * Returns the new interface's index on success, or -1 on failure.
 */
int
pf_netif_create(u_int type, const char *name, int flags)
{
	struct ifreq ifr;
	PF_NETIF *ifp;

	/* do we support this interface type */
	if (type > NB_IFTYPES) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_types[type].ift_opv == NULL) {
		pf_seterr(PF_ERR_NOTSUP);
		return (-1);
	}

	if ((ifp = pf_netif_alloc()) == NULL)
		return (-1);

	ifp->if_type = type;
	ifp->if_flags = flags & ~PFIF_INT_FLAGS;
	strlcpy(ifp->if_name, name, sizeof(ifp->if_name));

	if (pf_netif_add(ifp, -1) < 0)
		return (-1);

	if ((pf_netif_types[type].ift_opv->if_create != NULL) &&
	    (pf_netif_types[type].ift_opv->if_create(ifp) < 0)) {
		pf_netif_tab[ifp->if_index] = NULL;
		pf_netif_free(ifp);
		return (-1);
	}

	return (ifp->if_index);
}

/*
 * pf_netif_delete()
 *
 * Delete the network interface whose index is given in <nid>.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_delete(int nid)
{
	int ret;
	PF_NETIF *ifp;

	if ((nid < 0) || (nid > PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	if ((ret = pthread_mutex_lock(&pf_netif_mtx)) != 0) {
		return (-1);
	}
	ifp = pf_netif_tab[nid];

	if ((pf_netif_types[ifp->if_type].ift_opv->if_delete != NULL) &&
	    (pf_netif_types[ifp->if_type].ift_opv->if_delete(ifp) < 0))
		return (-1);

	pf_netif_free(pf_netif_tab[nid]);
	pf_netif_tab[nid] = NULL;
	(void)pthread_mutex_unlock(&pf_netif_mtx);

	return (0);
}


/*
 * pf_netif_getinfo()
 *
 * Retrieve information on the network interface whose index is given in <id>.
 */
int
pf_netif_getinfo(int id, struct pf_netif_info *info)
{
	PF_NETIF *ifp;

	if ((id < 0) || (id >= PFIF_MAXIF))
		return (-1);

	if (pf_netif_tab[id] == NULL)
		return (-1);

	ifp = pf_netif_tab[id];

	strlcpy(info->ifi_name, ifp->if_name, sizeof(info->ifi_name));
	info->ifi_index = ifp->if_index;
	info->ifi_type = ifp->if_type;
	info->ifi_mtu = ifp->if_mtu;
	info->ifi_flags = ifp->if_flags;

	info->ifi_hwalen = ifp->if_hwalen;
	if (ifp->if_hwalen > 0)
		memcpy(info->ifi_hwaddr, ifp->if_hwaddr, ifp->if_hwalen);

	return (0);
}



/*
 * pf_netif_add()
 *
 * Add an interface <nif> to the interface table, at index <id>.  If the
 * entry at the requested index is already used, an error will be returned.
 * If the <id> argument is -1, the first available slot will be assigned to
 * the new interface.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_add(PF_NETIF *nif, int id)
{
	int ret;

	ret = pthread_mutex_lock(&pf_netif_mtx);
	if (ret != 0) {
		return (-1);
	}

	if (id == -1) {
		for (id = 0; id < PFIF_MAXIF; id++)
			if (pf_netif_tab[id] == NULL)
				break;
		if (id == PFIF_MAXIF)
			return (-1);
	} else if (pf_netif_tab[id] != NULL)
		return (-1);

	pf_netif_tab[id] = nif;

	(void)pthread_mutex_unlock(&pf_netif_mtx);
	return (id);
}



/*
 * pf_netif_getindex()
 *
 * Returns the index of the interface whose name matches <ifname>, or -1 if
 * there is no such interface.
 */
int
pf_netif_getindex(const char *ifname)
{
	int i, id;

	id = -1;
	for (i = 0; i < PFIF_MAXIF; i++) {
		if ((pf_netif_tab[i] != NULL) &&
		    (strcmp(ifname, pf_netif_tab[i]->if_name) == 0)) {
			id = pf_netif_tab[i]->if_index;
			break;
		}
	}

	return (id);
}

/*
 * pf_netif_open()
 *
 * Open the interface for reading and writing by binding it to a datalink
 * device.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_open(int nid)
{
	u_int dltype;
	PF_NETIF *ifp;

	if ((nid < 0) || (nid >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	ifp = pf_netif_tab[nid];

	if (ifp->if_flags & PFIF_FL_VIRTUAL)
		dltype = PFDL_TYPE_PCAP;
	else
		dltype = PFDL_TYPE_ANY;

	ifp->if_dlink = pf_dlink_open(dltype);
	if (ifp->if_dlink == NULL)
		return (-1);

	if (pf_dlink_bind(ifp->if_dlink, ifp->if_index) < 0) {
		return (-1);
	}

	return (0);
}


/*
 * pf_netif_close()
 *
 * Close the network interface whose descriptor is given in <nid>.
 */
int
pf_netif_close(int nid)
{
	PF_NETIF *ifp;

	if ((nid < 0) || (nid >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	ifp = pf_netif_tab[nid];

	if (ifp->if_dlink == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	pf_dlink_close(ifp->if_dlink);
	ifp->if_dlink = NULL;

	return (0);
}


/*
 * pf_netif_recvpkt()
 *
 * Read data currently available on the network interface and dispatch it
 * appropriately.
 */
PF_PKT*
pf_netif_recvpkt(int id)
{
	PF_PKT *pkt;
	PF_NETIF *ifp;

	if ((id < 0) || (id >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (NULL);
	}
	else if (pf_netif_tab[id] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (NULL);
	}

	ifp = pf_netif_tab[id];
	if (ifp->if_dlink == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (NULL);
	}

	pkt = pf_dlink_read(ifp->if_dlink);
	if (pkt == NULL)
		return (NULL);

	pkt->pkt_if = ifp->if_index;

	if ((pf_netif_types[ifp->if_type].ift_opv->if_input != NULL) &&
	    (pf_netif_types[ifp->if_type].ift_opv->if_input(ifp, pkt) < 0)) {
		return (NULL);
	}

	return (pkt);
}

/*
 * pf_netif_sendpkt()
 *
 */
int
pf_netif_sendpkt(int nid, PF_PKT *pkt)
{


	return (0);
}

/*
 * pf_netif_alloc()
 *
 * Allocate a new network interface (pfnet_if) structure and return it.
 */
static PF_NETIF*
pf_netif_alloc(void)
{
	PF_NETIF *aif;

	aif = (PF_NETIF *)malloc(sizeof(*aif));
	if (aif != NULL) {
		memset(aif, 0, sizeof(*aif));
		aif->if_index = PFIF_INDEX_INVAL;
	}

	return (aif);
}


/*
 * pf_netif_free()
 *
 */
static void
pf_netif_free(PF_NETIF *ifp)
{
	free(ifp);
}


static int
pf_netif_xlateflags(int flags)
{
	int i, ret = 0;

	for (i = 0; i < (int)(sizeof(flags) * 8); i++)
		if (flags & (1 << i))
			ret |= pf_netif_fltab[i];

	return (ret);
}


/*
 * pf_netif_fromifreq()
 *
 * Gather the necessary information about a particular network interface
 * represented by <ifr> and create a system-independent pf_if structure
 * containing all the information.  The caller must somehow free the
 * allocated structure.
 * Returns a pointer to the allocated pf_if structure, or NULL on failure.
 */

static PF_NETIF*
pf_netif_fromifreq(int sock, struct ifreq *ifr)
{
	PF_NETIF *nif;
	struct ifreq ifrcp;

	nif = pf_netif_alloc();
	if (nif == NULL) {
		return (NULL);
	}
	strlcpy(nif->if_name, ifr->ifr_name, sizeof(nif->if_name));

	memcpy(&ifrcp, ifr, sizeof(ifrcp));
	if (ioctl(sock, SIOCGIFFLAGS, &ifrcp) == -1) {
	}
	nif->if_flags = pf_netif_xlateflags(ifrcp.ifr_flags);

	/* get the hardware address */
#if defined(__linux__)
	strlcpy(ifrcp.ifr_name, nif->if_name, sizeof(ifrcp.ifr_name));
	if (ioctl(sock, SIOCGIFHWADDR, &ifrcp) == -1) {
	}
	memcpy(nif->ifhwaddr, ifr->ifr_hwaddr.sa_data,
	    sizeof(nif->ifhwaddr));

	switch (ifr->ifr_hwaddr.sa_family) {
	case ARPHRD_ETHER:
	case ARPHRD_EETHER:
		nif->if_type = PFIF_TYPE_ETHER;
		nif->if_hwalen = 6;
		break;

	case ARPHRD_LOOPBACK:
		nif->if_type = PFIF_TYPE_LOOP;
		break;

	case ARPHRD_FDDI:
		nif->if_type = PFIF_TYPE_FDDI;
		break;

	case ARPHRD_IEEE80211:
		nif->if_type = PFIF_TYPE_IEEE80211;
		break;

	default:
		nif->if_type = PFIF_TYPE_OTHER;
		break;
	}
#endif

	if (ioctl(sock, SIOCGIFMTU, &ifrcp) == -1) {
		nif->if_mtu = 0;
	} else {
		nif->if_mtu = ifrcp.ifr_mtu;
	}

#if defined(__linux__)
	if (ioctl(sock, SIOCGIFINDEX, &ifrcp) == -1) {
	}
	else {
		nif->if_index = ifrcp.ifr_ifindex;
	}
#endif

	return (nif);
}


#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
/*
 * BSD version of the probe function, using the deceptively simple
 * getifaddrs() interface.
 */
static int
pf_netif_probe_bsd(void)
{
	int nbif, sock;
	size_t len;
	PF_NETIF *nif;
	struct ifreq ifr;
	struct if_data *ifdatp;
	struct ifaddrs *ifa, *ifp;
	struct ifmediareq ifm;
	struct sockaddr_dl *sdl;

	nbif = 0;
	if (getifaddrs(&ifa) == -1) {
		return (-1);
	}

	for (ifp = ifa; ifp != NULL; ifp = ifp->ifa_next) {
		/* we are only interested in link-level entries */
		if ((ifp->ifa_addr == NULL) ||
		    (ifp->ifa_addr->sa_family != AF_LINK))
			continue;

		sdl = (struct sockaddr_dl *)ifp->ifa_addr;
		ifdatp = (struct if_data *)ifp->ifa_data;

		if ((nif = pf_netif_alloc()) == NULL)
			return (-1);

		strlcpy(nif->if_name, ifp->ifa_name, sizeof(nif->if_name));
		nif->if_mtu = ifdatp->ifi_mtu;
		nif->if_flags = ifp->ifa_flags;
		nif->if_index = sdl->sdl_index;

		nif->if_hwalen = sdl->sdl_alen;
		if (nif->if_hwalen > 0)
			memcpy(nif->if_hwaddr, LLADDR(sdl),
			    sizeof(nif->if_hwaddr));

		switch (sdl->sdl_type) {
		case IFT_LOOP:
			nif->if_type = PFIF_TYPE_LOOP;
			break;
		case IFT_ETHER:
			nif->if_type = PFIF_TYPE_ETHER;
			break;
		case IFT_FASTETHER:
			nif->if_type = PFIF_TYPE_FASTETHER;
			break;
		case IFT_ISO88025:
			nif->if_type = PFIF_TYPE_TKNRING;
			break;
		case IFT_FDDI:
			nif->if_type = PFIF_TYPE_FDDI;
			break;
		case IFT_IEEE80211:
			nif->if_type = PFIF_TYPE_IEEE80211;
			break;
		case IFT_PPP:
			nif->if_type = PFIF_TYPE_PPP;
			break;
		case IFT_MODEM:
			nif->if_type = PFIF_TYPE_MODEM;
			break;
		case IFT_USB:
			nif->if_type = PFIF_TYPE_USB;
			break;
		case IFT_ISDN:
			nif->if_type = PFIF_TYPE_ISDN;
			break;
		default:
			nif->if_type = PFIF_TYPE_OTHER;
			break;
		}

#if 0
		memset(&ifm, 0, sizeof(ifm));
		strlcpy(ifm.ifm_name, ifp->ifr_name, sizeof(ifm.ifm_name));
		if (ioctl(sock, SIOCGIFMEDIA, &ifm) >= 0)
			nif->if_media = ifm.ifm_current;
#endif

		if (pf_netif_add(nif, nif->if_index) < 0) {
			pf_netif_free(nif);
			return (-1);
		}
		nbif++;
	}

	freeifaddrs(ifa);

	return (nbif);
}
#endif
